package ct.model;

/*
 * Classe de polynome pour la gestion des splines
 */
public class Polynomial {
	private double[] coeffs;

	public Polynomial(int degree) {
		coeffs = new double[degree + 1];
	}

	public Polynomial(double[] coeffs) {
		this.coeffs = coeffs;
	}

	public int getDegree() {
		return coeffs.length - 1;
	}

	public void setCoeff(double value, int degree) {
		this.coeffs[degree] = value;
	}

	public double getCoeff(int degree) {
		return this.coeffs[degree];
	}

	public String toString() {
		String result = String.valueOf(coeffs[0]);

		for (int i = 1; i < coeffs.length; i++) {
			result += " + " + coeffs[i] + " * X^" + i;
		}

		return result;
	}

	public Double eval(Double value) {
		double result = 0.;
		double deg = 1.;
		for (int i = 0; i < coeffs.length; i++) {
			result += (coeffs[i] * deg);
			deg *= value;
		}

		return result;
	}

	public Polynomial derive() {
		if (coeffs.length == 1) {
			return new Polynomial(0);
		}

		double[] coeff = new double[coeffs.length - 1];

		for (int i = 0; i < coeff.length; i++) {
			coeff[i] = coeffs[i + 1] * (i + 1);
		}

		return new Polynomial(coeff);
	}
}
